package 数组;

import java.util.ArrayList;

public class 螺旋数组 {
    public ArrayList<Integer> spiralOrder(int[][] matrix) {
        ArrayList<Integer> list = new ArrayList<>();
        if(matrix.length == 0) {
            return list;
        }
        int left = 0; //左边界
        int right = matrix[0].length-1; //右边界
        int top = 0 ; //上边界
        int bottom = matrix.length-1; //下边界
        while (true){
            //从左往右
            for (int i = left; i <= right; i++) {
                list.add(matrix[top][i]);
            }
            if (++top>bottom) break;
            //从上往下
            for (int i = top; i <= bottom; i++) {
                list.add(matrix[i][right]);
            }
            if (--right>left) break;
            //从右往左
            for (int i = right; i >= left;i--) {
                list.add(matrix[bottom][i]);
            }
            if (--bottom<top) break;
            //从下往上
            for (int i = bottom; i >= top; i--) {
                list.add(matrix[i][left]);
            }
            if (++left>right) break;
        }
            return list;


    }
}
